package org.example.controller;

import org.example.repository.OrderRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";
    private static final String APP_ID = "9021000149686287";
    private static final String PRIVATE_KEY ="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsmW4SRMTFESuNbWOFf7demydAs7AMK8LY+uvVXISrcL2zRw2CySEGUJkU7kQeEVqe4RnPCQ5qOCb6bliZc0Cha9nOyzqmJyjDTuJH1tuiFk3vwatWFXNN2XBaMmz6hBp+uFPtEZdqyEhKSl9ccqv5cEuvrcNEkeCV5kdjZ3HDS8pyftdHRAx5rxER1LD1XsSwKGyX4kTpYbBLz/LkqGd2hDvmvVACKu2yuSQMztZsX27+oy6X0Db1Xgh4GTMS0U30jQrZpl0aOJhjwEas9VO/5RXO3h6q+gTB20kY7xmX9KZWLszZO84SYBhCOCApj4F3nk5qaZBoOU2tFddifps9AgMBAAECggEADcVsJ97+yC53iCA7OZKYId9FQX9Uw5PWRxO2L17jYv5q1FwN8upzTRqvLCFao/+EeHrDYWZ6lPUH/yFAxnWQqZB+X2aNtmYXdYXcvhihi4w2CbQtJIAvo/1+XmP5l/9kUcoJQDgQGcADLJJEi47Gs+9GyqyVkOoGvk8SURcW15sZs/6E6rQuPrPKZJirYVwh9wGKFuPDh/MVUlFRgZgW7eXX1cu6XKFYkKdbfgK5XnFe5eCv0aC01fTursizKTABLveoRMkmsk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som1qLjcsUahP/i8B8f/pc1ZncETrBok/qupU9o8HVtYYqaGnmxTpYgcZ4zUj4nKRvWdQIJoIos8FoUk8A1MoYOxwYVCFoFssrEN8w8sGxPorejXTfQdBMYWcNQNOveOQASLJPoEgBWsDU70L0YHeLz5dtim3JUyMku7h9PygoKBV5A6ZReQBZ5FbiefN2qZNOBKXg4le9v8vdJn+ulaH3QaPw8f3v4YKu/rt4e6MuKAkyq8AgajAszpNRsBGm48eClXLOCrXPvkhX17QIDAQAB";

    @Resource
    OrderRepository orderhistoryService;

    @GetMapping("/pay/{tradeNo}/{subject}/{totalAmount}")
    public void pay(@PathVariable("tradeNo") String tradeNo, @PathVariable("subject") String subject, @PathVariable("totalAmount") String totalAmount, HttpServletResponse httpResponse) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID,
                PRIVATE_KEY, FORMAT, CHARSET, PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl("http://r27d86b4.natappfree.cc/alipay/notify");
//        List<Orderhistory> all = orderhistoryService.getAll();
//        Orderhistory orderhistory = all.stream().filter(o -> Objects.equals(id, o.getId())).findFirst().orElse(null);
//        if (orderhistory == null) {
//            return;
//        }
//        orderhistory.setOrderStatus(3);
//        orderhistory.setStatus("已支付");
//        orderhistoryService.update(orderhistory);
        UUID uuid = UUID.randomUUID();
        request.setBizContent("{\"out_trade_no\":\"" + tradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + ""+subject+"" + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
}
